package NewTmas.FramesandPanels;

import NewTmas.Listeners.ColumnShowListener;
import NewTmas.Listeners.PeriodicRefreshListener;
import NewTmas.Listeners.PrintGraphMenuListener;
import NewTmas.Listeners.TasksTablePopupListener;
import taskmaster.auth.User;
import taskmaster.job.QueryParams;
import taskmaster.job.Task;
import taskmaster.job.TaskBuilder;
import taskmaster.job.TaskCollection;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.*;

public class IntFrame extends JInternalFrame
{

    private static final long serialVersionUID = 1L;

    public int width,height;
    User user;

    TaskBuilder tb;
    QueryParams limiters;

    Connection connection;
    Date date;

    TablePanel tablepanel;

    List<JobGraphPanel> graphPanels=new ArrayList<JobGraphPanel>()  ;
    JDesktopPane dtp;

    HashSet<String> jobSet;

    TaskCollection taskCollection;

    HashMap<String,String> signoffMap;

    Task[] filteredTasks;
    JTabbedPane tabbedPane = new JTabbedPane();
    String selectedLib ;
    SimpleDateFormat dateformat=new SimpleDateFormat("MMM dd,yyyy h:mm:ss a");

    public IntFrame(TaskCollection tc,QueryParams limiters, Date date, String lib, User user, TaskBuilder tb, JDesktopPane dtp,HashMap<String, String> signoffMap,int width,int height) {
        this.date = date;
        this.user = user;
        this.tb = tb;
        this.connection = user.getConnection();
        this.dtp = dtp;
        this.selectedLib =lib ;
        this.signoffMap=signoffMap;
        this.limiters=limiters;
        this.height=height;
        this.width=width;
        this. taskCollection = tc;
        this.width=width;
        this.height =height;
        if (taskCollection.isEmpty())
        {
            JOptionPane.showMessageDialog(this, "No matching tasks found.Try again", "No Tasks found", 0);
            setVisible(false);

        } else
        {
            createFrame(selectedLib, tb, dtp);
        }

    }



    public IntFrame(String[] joblistSelectedValues, Date selectedDate, String[] jobcategory, int[] rolelistSelectedValues, final String selectedLib, User u, final TaskBuilder tb, final JDesktopPane dtp, HashMap<String, String> signoffMap,int width,int height)
    {

        this.date = selectedDate;
        this.user = u;
        this.tb = tb;
        this.connection = user.getConnection();
        this.dtp = dtp;
        this.selectedLib =selectedLib ;
        this.signoffMap=signoffMap;
          this.height=height;
        this.width=width;
        Set<String> categoryHash = new HashSet<String>();
        categoryHash.addAll(Arrays.asList(jobcategory));

        limiters = new QueryParams(rolelistSelectedValues, joblistSelectedValues, categoryHash, new char[0], date, true);


        try
        {
            taskCollection = tb.getTaskCollection(limiters, user);
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(null, "Problem creating the TaskCollection object : "+e.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
            throw new RuntimeException(e);
        }


        if (taskCollection.isEmpty())
        {
            JOptionPane.showMessageDialog(this, "No matching tasks found.Try again", "No Tasks found", 0);
            setVisible(false);

        } else
        {
            createFrame(selectedLib, tb, dtp);
        }


    }

    private void createFrame(String selectedLib, TaskBuilder tb, JDesktopPane dtp) {
        dtp.add(this);
        toFront();
        setTitle(limiters.getDisplayString());
        setVisible(true);
        setSize(800, 700);
        setResizable(true);
        setMaximizable(true);
        setClosable(true);
        setIconifiable(true);
        this.filteredTasks=taskCollection.getAllTasksArray() ;
        jobSet=getJobSetforCollection(filteredTasks);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        add(tabbedPane);

        tablepanel = new TablePanel(taskCollection, tb, limiters, user);
        tabbedPane.addTab("Table View", new ImageIcon(IntFrame.class.getResource("/Resources/Icons/table.png")), new JScrollPane(tablepanel.getTable()), "click to view the Tasks table");
        Iterator<String> iter = jobSet.iterator();

        while (iter.hasNext())
        {
            String jobname = iter.next();
            graphPanels.add(new JobGraphPanel(jobname, date, tb, user, dtp, tablepanel, taskCollection,selectedLib,this));
        }

        for(JobGraphPanel j:graphPanels){
            JPanel graphPanel = j.makeGraphPanel();

            tabbedPane.addTab(j.job, new ImageIcon(IntFrame.class.getResource("/Resources/Icons/graph.png")), graphPanel, "click to view the graph");

        }


        JMenuBar menubar = new JMenuBar();
        setJMenuBar(menubar);
        JMenu actions = new JMenu("Actions");
        menubar.add(actions);


        JMenu showColumns=new JMenu("Show Columns");
        for(int i=0;i<tablepanel.tcTable.getColumnModel().getColumnCount();i++){
            JCheckBoxMenuItem item;
            showColumns.add(item=new JCheckBoxMenuItem(tablepanel.tcTable.getColumnName(i),true))   ;
            item.addItemListener(new ColumnShowListener(tablepanel,i));

        }

        menubar.add(showColumns);

        JMenuItem refreshOnce =new JMenuItem("Refresh Once")    ;
        refreshOnce.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, java.awt.Event.CTRL_MASK));
        refreshOnce.setMnemonic(KeyEvent.VK_F5);

        refreshOnce.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {

                toRefresh() ;
            }
        });



       JMenu refreshMenu=new JMenu("Refresh Every");
         final ActionListener refreshtimer=new ActionListener() {
        public void actionPerformed(ActionEvent e) {
           toRefresh();
        }
    } ;

          //creating refresh every menu
       int[] timeInterval=new int[]{30,60,600,3600};                       //time interval in seconds

        for(int i=0;i<timeInterval.length;i++){
            String suffix=new String();

            if(timeInterval[i]<60) {
                suffix=String.valueOf(timeInterval[i]) +" s" ;
            }

            if(timeInterval[i]>=60 && timeInterval[i]<3600)
            {
                int minutes=  ((timeInterval[i]/60) % 60);
                suffix=String.valueOf(minutes) +" min" ;

            }

            if(timeInterval[i]>=3600){
                int hours=(timeInterval[i]/3600) % 24;
                suffix=String.valueOf(hours) +" hr" ;
            }
            final JCheckBoxMenuItem refreshEvery = new JCheckBoxMenuItem(suffix);
             refreshEvery.addItemListener(new PeriodicRefreshListener(refreshtimer,timeInterval[i]*1000,graphPanels,suffix ));
            refreshMenu.add(refreshEvery);

        }


         actions .add(refreshOnce);
         actions .add(refreshMenu);

        JMenu printGraphs=new JMenu("Print");
        printGraphs.addMenuListener(new PrintGraphMenuListener(jobSet,printGraphs,graphPanels,selectedLib));
        menubar.add(printGraphs);


        tablepanel.tcTable.addMouseListener(new TasksTablePopupListener(graphPanels, tablepanel));
    }


    public TaskCollection getTaskCollection() {
        return taskCollection;
    }

    public void toRefresh() {


        try
        {
            taskCollection=tb.getTaskCollection(limiters,user);
        } catch (Exception ex)
        {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }

        for(String s:getJobSetforCollection(taskCollection.getAllTasksArray()))
        {

            if(!jobSet.contains(s))
            {     JobGraphPanel j=null;
                jobSet.add(s);
                graphPanels.add(j=new JobGraphPanel(s,date,tb,user,dtp,tablepanel,taskCollection ,this.selectedLib,this));
                JPanel graphPanel = j.makeGraphPanel();

                tabbedPane.addTab(j.job, new ImageIcon(IntFrame.class.getResource("/Resources/Icons/graph.png")), graphPanel, "click to view the graph");
            }
        }
        tablepanel.refreshTaskTablePanel(taskCollection);
        for (JobGraphPanel graphPanel : graphPanels)
        {
            graphPanel.refreshGraph(taskCollection);
            graphPanel.lastrefreshedAt.setText("Last Refreshed: "+dateformat.format(Calendar.getInstance().getTime()));
        }

    }




    public static Task[] getTaskArrayforJob(TaskCollection taskCollection, String jobName)
    {

        Task[] allTasksArray = taskCollection.getAllTasksArray();
        HashSet<Task> tasksforJob = new HashSet<Task>();
        for (int i = 0; i < allTasksArray.length; i++)
        {
            String str = allTasksArray[i].getJobTag();
            if (str.equalsIgnoreCase(jobName))
            {
                tasksforJob.add(allTasksArray[i]);
            }
        }

        Task[] jobTasks = new Task[tasksforJob.size()];
        jobTasks = tasksforJob.toArray(jobTasks);

        return jobTasks;
    }

    public HashSet<String> getJobSetforCollection(Task[] filteredTasks) {
        HashSet<String> jobSet;

        jobSet = new HashSet<String>();
        for (int i = 0; i < filteredTasks.length; i++)
        {
            jobSet.add(filteredTasks[i].getJobTag());

        }
        return jobSet;
    }





}